package org.pizza.rocket.core.support;

import com.aliyun.openservices.ons.api.Message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 高巍
 * email kynb_club@163.com
 * @since 2020/11/24 3:22 下午
 * 消息建造者（可有效控制消息body的正反序列化）
 */
public final class MessageBuilder {
    private Object body;
    private String topic;
    private String tag;
    private String key;
    private long delayTime;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public MessageBuilder() {
    }

    public static  MessageBuilder builder() {
        return new MessageBuilder ();
    }

    public MessageBuilder tag(String tag) {
        this.tag = tag;
        return this;
    }

    public MessageBuilder topic(String topic) {
        this.topic = topic;
        return this;
    }

    public MessageBuilder key(String key) {
        this.key = key;
        return this;
    }
    public MessageBuilder delayTime(long delayTime) {
        this.delayTime = delayTime;
        return this;
    }

    public MessageBuilder body(Object data) {
        this.body = data;
        return this;
    }

    public Message build() {
        Message message = new Message();
        message.setTag(this.tag);
        message.setTopic(this.topic);
        message.setKey(this.key);
        message.setStartDeliverTime(this.delayTime);
        try {
            message.setBody(objectMapper.writeValueAsBytes(this.body));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return message;
    }
}
